﻿using llm_net.Services.Abstractions;
using llm_project.Infrastructure.Helpers;
using llm_project.Models;
using Microsoft.AspNetCore.Builder.Extensions;
using Microsoft.Extensions.Options;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json.Serialization;
using static llm_net.Infrastructure.Extensions.ServiceCollectionExtensions;

namespace llm_net.Services.Implementations
{
    public class TongyiApiService: ITongyiApiService
    {
        private readonly TongyiApiOptions _apiOptions;
        private readonly ILogger<TongyiApiService> _logger;

        public TongyiApiService(HttpClient httpClient, IConfiguration configuration, ILogger<TongyiApiService> logger, IOptions<TongyiApiOptions> apiOptions)
        {
            _apiOptions= apiOptions.Value;
            _logger = logger;
            HttpClientSingleton.ConfigureApiHeaders(_apiOptions.AppKey);
        }
        public async Task<float[]> GetTextEmbeddingAsync(string text)
        {
            _logger.LogInformation($"请求文本嵌入: {text}");

            try
            {
                // 构建符合OpenAI兼容API的请求体
                var requestBody = new
                {
                    model = "text-embedding-v1", // 必需的model参数
                    input = new[] { text }
                };

                var content = new StringContent(
                    System.Text.Json.JsonSerializer.Serialize(requestBody),
                    Encoding.UTF8,
                    "application/json"
                );
                // 使用兼容OpenAI的API路径
                using var response = await HttpClientSingleton.GetClient().PostAsync(
                    $"{_apiOptions.Endpoint}/compatible-mode/v1/embeddings",
                    content
                );
                // 检查响应状态
                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    _logger.LogError($"API返回错误 - StatusCode: {response.StatusCode}, Content: {errorContent}");
                    throw new HttpRequestException($"API错误: {errorContent}", null, response.StatusCode);
                }

                // 解析响应（根据OpenAI兼容格式调整）
                var jsonResponse = await response.Content.ReadAsStringAsync();
                return ParseEmbeddingResponse(jsonResponse);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "调用百炼API失败");
                throw;
            }
        }

        // 调整解析逻辑以匹配OpenAI兼容格式
        private float[] ParseEmbeddingResponse(string jsonResponse)
        {
            try
            {
                var response = System.Text.Json.JsonSerializer.Deserialize<EmbeddingResult>(jsonResponse);

                if (response?.Data?.Any() == true && response.Data[0].Embedding?.Any() == true)
                {
                    return response.Data[0].Embedding.Select(v => (float)v).ToArray();
                }

                throw new InvalidOperationException("未能解析嵌入向量");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"解析API响应失败: {jsonResponse}");
                throw;
            }
        }
    }
}
